﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;

public class GyroTestScript : MonoBehaviour
{
    private AndroidJavaObject plugin;


    void Start()
    {
        Input.gyro.enabled = true;

        #if UNITY_ANDROID
        plugin = new AndroidJavaClass("jp.kshoji.unity.sensor.UnitySensorPlugin").CallStatic<AndroidJavaObject>("getInstance");
        plugin.Call("setSamplingPeriod", 10 * 1000); // refresh sensor 100 mSec each
        plugin.Call("startSensorListening", "rotationvector");
#endif
    }

    void Update()
    {
        var text = GetComponent<Text>();
        Input.gyro.enabled = true;
        //text.text = SystemInfo.supportsGyroscope ? Input.gyro.attitude.ToString() : "NO AVAILABLE";

        //#if UNITY_ANDROID
        if (plugin != null)
        {
            float[] sensorValue = plugin.Call<float[]>("getSensorValues", "accelerometer");
            if (sensorValue != null)
            {
                text.text = string.Join(",,", new List<float>(sensorValue).ConvertAll(i => i.ToString()).ToArray());
            }
        }
        //#endif
    }

    void OnApplicationQuit()
    {
        #if UNITY_ANDROID
        if (plugin != null)
        {
            plugin.Call("terminate");
            plugin = null;
        }
        #endif
    }
}
